package com.caowei.weicimpress.weicimpress;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.HeaderViewListAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.caowei.weicimpress.weicimpress.widget.AlertDialog;
import com.caowei.weicimpress.weicimpress.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by caoweiPc on 2014/7/15.
 */
public class SysFileFragment extends ActionBarBaseFragment implements FileInfoAdapter.EnableOrDisableBtnBySelectedCheckBoxes {
    public final static String INPUTPASSWD_ACTION=SysFileFragment.class.getName()+".action.VIEW";
    public final static int REQUESTCODE=0;
    public final static int REQUESTCODE_PASSWD=1;
    private final static String TAG=SysFileFragment.class.getSimpleName();
    private final static int extract0="extract0".hashCode();
    private final static int compress0="compress0".hashCode();
    private final static int extract1="extract1".hashCode();
    private final static int tag=R.id.dirOk;
    ArrayList<FileInfoBean>  isEncriedBeans;
    ArrayList<FileInfoBean>  isNotEncriedBeans;
    private boolean navigateToCompressFrgAble=true;
    @Override
    protected void init() {
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            rootFile=Environment.getExternalStorageDirectory();
        }else{
            rootFile= Environment.getRootDirectory();
        }
        actionItemWithFileInfoBean=new ActionItemWithFileInfoBean();
    }

    @Override
    protected String[] getItemLongClickMenu(FileInfoBean bean) {
        String menu[]=null;
        menu=getActivity().getResources().
                getStringArray(R.array.sysfilefragment_longitemclick);
        return menu;
    }

    @Override
    protected void exeDialogOper(int position, final FileInfoBean bean){
        switch (position) {
            case 0:
                if(Utils.DEBUG){
                    Log.d(TAG, position + "");
                }
                String filePath=bean.getParentPath()+File.separator+bean.getFileName();
                File file=new File(Utils.normalizePath(filePath));
                String title="";
                List<GenerateDialog.ActionItem> actionItems=new ArrayList<GenerateDialog.ActionItem>();
                String items[]=null;
                String fileProperties[][]=null;
                if(file.isDirectory()){
                    title=getActivity().getResources().getString(R.string.dirpropertyname);
                    fileProperties=new String[][]{
                        new String[]{bean.getFileName()},
                            new String[]{bean.getParentPath()},
                        new String[]{Utils.formateDate(file.lastModified(),Utils.DEFAULTDATEPATTERNWITHA)},
                        new String[]{String.valueOf(bean.getNumOfSubFile())},
                        new String[]{String.valueOf(file.canRead())},
                        new String[]{String.valueOf(file.canWrite())},
                        new String[]{Utils.normalSizeStr(Utils.getInternalFreeAllSpace()),
                                Utils.normalSizeStr(Utils.getExternalFreeAllSpace())},
                        new String[]{Utils.normalSizeStr(Utils.getInternalAllSpace()),
                                Utils.normalSizeStr(Utils.getExternalAllSpace())}
                    };
                    items= getActivity().getResources().getStringArray(R.array.dirproperty);
                }else{
                    title=getActivity().getResources().getString(R.string.filepropertyname);
                    items= getActivity().getResources().getStringArray(R.array.fileproperty);
                    fileProperties=new String[][]{
                            new String[]{bean.getFileName()},
                            new String[]{bean.getParentPath()},
                            new String[]{Utils.formateDate(file.lastModified(),Utils.DEFAULTDATEPATTERNWITHA)},
                            new String[]{ Utils.normalSizeStr(bean.getSize()) },
                            new String[]{String.valueOf(file.canRead())},
                            new String[]{String.valueOf(file.canWrite())},
                            new String[]{ Utils.normalSizeStr(Utils.getInternalFreeAllSpace()),
                                    Utils.normalSizeStr(Utils.getExternalFreeAllSpace())},
                            new String[]{Utils.normalSizeStr(Utils.getInternalAllSpace()),
                                    Utils.normalSizeStr(Utils.getExternalAllSpace())}
                    };
                }
                if(items!=null){
                    for(int i=0;i<items.length;i++){
                        GenerateDialog.ActionItem actionItem=new GenerateDialog.ActionItem();
                        String item=String.format(items[i],(Object[])fileProperties[i]);
                        actionItem.setName(item);
                        actionItems.add(actionItem);
                    }
                }
                GenerateDialog.createSelectOperDialog(title,getActivity(),
                        actionItems).show();
                break;
            case 1:
                Log.d(TAG, position + "");
                Intent i=new Intent(getActivity(),OperationCompressActivity .class);
                //todo  bean信息要传过去
                i.putExtra("bean",bean);
                startActivityForResult(i, SysFileFragment.REQUESTCODE);
                break;
            case 2:
                String msg;
                if(!bean.isCompressed()){
                    msg="非压缩文件";
                    Toast.makeText(getActivity(),msg,Toast.LENGTH_SHORT).show();
                }else if(bean.isCompressed()){
                   /* msg="选择解压目录";
                    Toast.makeText(getActivity(),msg,Toast.LENGTH_SHORT).show();
                    mListView.setLongClickable(false);
                    footer3.setVisibility(View.VISIBLE);
                    footer3.setTag(tag,extract0);
                    dirOk.setTag(bean);
                    enableMlistViewCheckbox(false);*/
                    extract(bean);
                }
                if(Utils.DEBUG){
                    Log.d(TAG, position + "");
                }
                break;
            case 3:
                if(Utils.DEBUG){
                    Log.d(TAG, position + "");
                }
                final MyApplication application= (MyApplication) getActivity().getApplication();
                String fileName= Utils.normalizePath((new StringBuilder(bean.getParentPath())).append(File.separator).
                append(bean.getFileName()).toString());
                if(!bean.isDir()){
                    fileName=Utils.dropTailStr(fileName,File.separator);
                }
                final String fileN=fileName;
                String verify=getActivity().getResources().getString(R.string.verify_title);
                com.caowei.weicimpress.weicimpress.widget.AlertDialog dialog1= GenerateDialog.createVerifyDialog(getActivity(), verify, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showCoverProgress(true,getActivity().getResources().getString(R.string.deleting));
                        AsyncTask myAsyncTask = new AsyncTask<Object, Object, Boolean>() {
                            @Override
                            protected Boolean doInBackground(Object[] params) {
                                boolean result = Utils.del(fileN);
                                return result;
                            }
                            @Override
                            protected void onPostExecute(Boolean aBoolean) {
                                showCoverProgress(false,null);
                                if (aBoolean) {
                                    Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.success_del),
                                            Toast.LENGTH_SHORT).show();
                                    refresh();
                                } else {
                                    Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.fail_del),
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        };
                        myAsyncTask.execute(application);
                    }
                }, null);
                dialog1.show();
                break;
        }
    }

    public void extract(FileInfoBean bean){
        String msg="选择解压目录";
        Toast.makeText(getActivity(),msg,Toast.LENGTH_SHORT).show();
        mListView.setLongClickable(false);
        footer3.setVisibility(View.VISIBLE);
        footer3.setTag(tag,extract0);
        dirOk.setTag(bean);
        enableMlistViewCheckbox(false);
    }

    @Override
    protected void onSubItemClick(AdapterView<?> parent, View view, int position, long id) {
        FileInfoAdapter.ViewHolder viewHolder= (FileInfoAdapter.ViewHolder) view.getTag();
        //todo  以后前后插入代码
        Log.d(TAG, "onSubItemClick");
        FileInfoBean bean= viewHolder.getBean();
        if(!bean.isDir()){
            final String filePath=Utils.normalizePath(bean.getParentPath()+ File.separator+
                    bean.getFileName());

            ExecuteFileHandler executeFileHandler1= ExecuteFileHandler.getInstance();
            //todo   先这样吧 以后说
            if(executeFileHandler1.checkCompressNoFinished(bean)){
                Toast.makeText(getActivity(),"文件正在处理中...",Toast.LENGTH_SHORT).show();
                return;
            }
            showCoverProgress(true,getActivity().getResources().
                    getString(R.string.reading,bean.getFileName()));

            AsyncTask<Object,Object,Boolean> asyncTask=new AsyncTask<Object, Object, Boolean>() {
                @Override
                protected Boolean doInBackground(Object... params) {
                    return executeFileHandler.isCompressFile(new File(filePath));
                }
                @Override
                protected void onPostExecute(Boolean b) {
                    if(!b){
                        Toast.makeText(getActivity(),getActivity().getResources().getString(
                                R.string.isnotcompressfile), Toast.LENGTH_SHORT).show();
                    }else{
                        if(navigateToCompressFrgAble){
                          /*  Bundle argument=new Bundle();
                            argument.putString("filePath",filePath);*/
                            ((OnSwitchFragment)getActivity()).switchFragment(CompressFileFragment.class,new Callback() {
                                @Override
                                public void onCallback(Callback1 callback) {
                                    callback.onCallback(SysFileFragment.class,filePath);
                                }
                            });
                        }
                    }
                    showCoverProgress(false,null);
                }
            };

            if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB){
                asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            }else{
                asyncTask.execute();
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode== Activity.RESULT_OK){
            if(requestCode==REQUESTCODE){
                dirOk.setTag(data);
                mListView.setLongClickable(false);
                if(footer3.getVisibility()!=View.VISIBLE){
                    footer3.setVisibility(View.VISIBLE);
                }
                enableMlistViewCheckbox(false);
                footer3.setTag(tag,compress0);
                enablefooterBtnes();
            }else if(requestCode==REQUESTCODE_PASSWD){
                isEncriedBeans=data.getParcelableArrayListExtra("beans");
                List<FileInfoBean> datas=new ArrayList<FileInfoBean>();
                datas.addAll(isEncriedBeans);
                isEncriedBeans.clear();
                isEncriedBeans=null;
                datas.addAll(isNotEncriedBeans);
                isNotEncriedBeans.clear();
                isNotEncriedBeans=null;
                String currentDirStr=data.getStringExtra("currentDir");
                File currentDir=new File(currentDirStr);
                String saveName=data.getStringExtra("saveName");
                String preMsg=data.getStringExtra("preMsg");
                executeExtract(currentDir,saveName,datas,new StringBuilder(preMsg));
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id=v.getId();
        Activity activity=getActivity();
        switch (id){
            case R.id.dirCancel:
                v.setEnabled(false);
                if(footer3.getVisibility()==View.VISIBLE){
                    footer3.setVisibility(View.GONE);
                }
                mListView.setLongClickable(true);
                if(navigateToCompressFrgAble){
                    cancelAllMlistViewCheckbox();
                }
                enableMlistViewCheckbox(true);
                if(footer2.getVisibility()==View.VISIBLE){
                    footer2.setVisibility(View.GONE);
                }
                navigateToCompressFrgAble=true;
                if(activity instanceof GetFragment){
                    GetFragment getCorrespondFragment= (GetFragment) activity;
                    CompressFileFragment fragment= (CompressFileFragment) getCorrespondFragment.
                            get(Utils.COMPRESSFRAG_TAB_INDEX);
                    fragment.showCoverLayout(false);
                }
                enablefooterBtnes();
                break;
            case R.id.footer2_4:
                List<FileInfoBean> selectedBeans=getSelectedItems();
                String msg="选择解压目录";
                Toast.makeText(getActivity(),msg,Toast.LENGTH_SHORT).show();
                mListView.setLongClickable(false);
                footer3.setVisibility(View.VISIBLE);
                footer3.setTag(tag,extract0);
                dirOk.setTag(selectedBeans);
                enableMlistViewCheckbox(false);
                break;
            case R.id.dirOk:
                v.setEnabled(false);
                if(footer3.getVisibility()==View.VISIBLE){
                    footer3.setVisibility(View.GONE);
                }

                TextView textView=findPathPathOnAtionbarLayout();
                final String currentDirStr=textView.getText().toString();
                if(footer3.getTag(tag).equals(extract0)){
                    Object o=dirOk.getTag();
                    FileInfoBean bean=null;
                    List<FileInfoBean> beans=null;
                    if(o instanceof FileInfoBean){
                        bean= (FileInfoBean) o;
                    }else if(o instanceof List){
                        beans= (List<FileInfoBean>) o;
                    }

                    final ArrayList<FileInfoBean> beans1=new ArrayList<FileInfoBean>();
                    if(beans!=null&&!beans.isEmpty()){
                        Log.d(TAG,"beans");
                        bean=beans.get(0);
                        beans1.addAll(beans);
                    }else{
                        beans1.add(bean);
                    }
                    final File currentDir=new File(currentDirStr);
                    final FileInfoBean bean1=bean;
                    final String saveName=Utils.dropDotSuffix(bean.getFileName());
                    final File file=new File(Utils.normalizePath(currentDirStr+File.separator+
                            saveName));
                    final StringBuilder taskNameSb=new StringBuilder();
                    taskNameSb.append("解压文件:").append(bean1.getFileName());
                    final View.OnClickListener yesListener=new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String saveName1=saveName;
                            if(v!=null&&v.getTag()!=null){
                                saveName1= (String) v.getTag();
                            }
                            inputPasswdToFileInfobean(beans1,
                                    currentDir, saveName1, taskNameSb.toString());
                        }
                    };

                    if(file.exists()){
                        GenerateDialog.BtnBean btn1=new GenerateDialog.BtnBean();
                        btn1.setBtnText("确定?");

                        GenerateDialog.BtnBean btn2=new GenerateDialog.BtnBean();
                        btn2.setBtnText("修改?");

                        GenerateDialog.BtnBean btn3=new GenerateDialog.BtnBean();
                        btn3.setBtnText("取消?");

                        GenerateDialog.BtnBean[] btnes=new GenerateDialog.BtnBean[]{
                                btn1,
                                btn2,
                                btn3
                        };
                        StringBuilder sb=new StringBuilder();
                        sb.append("覆盖目录:").append(file.getName()).append("?");
                        final AlertDialog dialog= GenerateDialog.createVerifyDialog(getActivity(),sb.toString(),btnes);
                        btn1.setListener(new View.OnClickListener(){
                            @Override
                            public void onClick(View v) {
//                                Utils.del(file.getAbsolutePath());
                                yesListener.onClick(v);
                            }
                        });
                        btn2.setListener(new View.OnClickListener(){
                            @Override
                            public void onClick(View v) {
                                AlertDialog dialog1= GenerateDialog.createInputDialog("填写解压目录名:",getActivity()
                                        ,new GenerateDialog.OnClickListener() {
                                            @Override
                                            public void onClick(View v,GenerateDialog.CallbackDismiss callbackDismiss) {
                                                String newName= (String) v.getTag();
                                                File path=new File(Utils.dropTailStr(Utils.normalizePath(currentDirStr+
                                                        File.separator+newName),File.separator));
                                                if(path.exists()){
                                                     callbackDismiss.onDismiss(false);
                                                    return;
                                                }else{
                                                    callbackDismiss.onDismiss(true);
                                                }
                                                yesListener.onClick(v);
                                            }
                                        }, new GenerateDialog.OnClickListener() {
                                            @Override
                                            public void onClick(View v,GenerateDialog.CallbackDismiss callbackDismiss) {
                                                dialog.show();
                                                callbackDismiss.onDismiss(true);
                                         }
                                });
                                dialog1.show();
                            }
                        });
                        btn3.setListener(null);
                        dialog.show();
                    }else{
                        yesListener.onClick(null);
                    }
                    //=================================================================
                }else if(footer3.getTag(tag).equals(compress0)){
                    final Intent intent= (Intent) dirOk.getTag();

                    final FileInfoBean compressedFileBean=intent.getParcelableExtra("bean");

                    final List<FileInfoBean> beans=intent.getParcelableArrayListExtra("beans");
                    StringBuilder sb=new StringBuilder();

                    if(beans==null||(beans!=null&&beans.isEmpty())){
                        sb.append(getActivity().getResources().getString(R.string.compressoper,
                                compressedFileBean.getFileName()));
                    }else{
                        sb.append(getActivity().getResources().getString(R.string.compressoper,
                                beans.get(0).getFileName())).
                                append(getActivity().getText(R.string.omit));
                    }
                    final String taskName=sb.toString();
                    final String fileHandlerClsName=intent.getStringExtra("handler");
                    final FileHandler fileHandler=ExecuteFileHandler.getInstance().
                            getHandlerByClsName(fileHandlerClsName);
                    final String passwd=intent.getStringExtra("passwd");
                    final int compressmethod_key=intent.getIntExtra("compressmethod_key",-1);
                    final int subsize=intent.getIntExtra("subsize",0);
                    final String unit=intent.getStringExtra("selectedUnit");

                    final String saveName=intent.getStringExtra("saveName");
                    final String nameOfFormat=intent.getStringExtra("nameOfFormat");
                    StringBuilder sbTargetName=new StringBuilder(currentDirStr);
                    sbTargetName.append(File.separator).append(saveName).append(".").append(nameOfFormat);
                    final File saveFile_g=
                            new File(Utils.normalizePath(sbTargetName.toString()));
                    View.OnClickListener verifyOkListener=  new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            MyAsyncTask task=new MyAsyncTask<Object,Object, FileHandler.MainPartFile >() {
                                @Override
                                protected  FileHandler.MainPartFile  doInBackground(Object[] params){
                                    File saveFile=saveFile_g;
                                    FileHandler.MainPartFile mainPartFile=new FileHandler.MainPartFile();
                                    if(beans==null||(beans!=null&&beans.isEmpty())){
                                        List<FileInfoBean> beans1=new ArrayList<FileInfoBean>();
                                        File inputFile=new File(Utils.normalizePath(compressedFileBean.getParentPath()+
                                                File.separator+compressedFileBean.getFileName()));
                                        if(saveFile.exists()&&saveFile.equals(inputFile)){
                                            StringBuilder sbInput=new StringBuilder(currentDirStr);
                                            sbInput.append(File.separator).append(saveName).append("-").
                                                    append(System.currentTimeMillis()).append(".").
                                                    append(nameOfFormat);
                                            File saveFile1=new File(Utils.normalizePath(
                                                    sbInput.toString()));
                                            saveFile=saveFile1;
                                        }
                                        if( saveFile.exists()){
                                            saveFile.delete();
                                        }
                                        beans1.add(compressedFileBean);
                                        if(subsize<=0){
                                            File returnFile= fileHandler.compress(saveFile,passwd,compressmethod_key,beans1);
                                            mainPartFile.mainFile=returnFile;
                                        }else{
                                            mainPartFile = fileHandler.compress(saveFile,passwd,compressmethod_key,beans1,subsize,unit);
                                        }
                                    }else{
                                       for(FileInfoBean bean:beans){
                                            File inputFile=new File(Utils.normalizePath(bean.getParentPath()+
                                                    File.separator+bean.getFileName()));
                                            if(saveFile.exists()&&saveFile.equals(inputFile)){
                                                StringBuilder sbInput=new StringBuilder(currentDirStr);
                                                sbInput.append(File.separator).append(saveName).append("-").
                                                        append(System.currentTimeMillis()).append(".").
                                                        append(nameOfFormat);
                                                saveFile=new File(Utils.normalizePath(sbInput.toString()));
                                                break;
                                            }
                                        }
                                        if(saveFile.exists()){
                                            saveFile.delete();
                                        }
                                        if(subsize<=0){
                                            File returnFile= fileHandler.compress(saveFile,passwd,compressmethod_key,beans);
                                            mainPartFile.mainFile=returnFile;
                                        }else{
                                            mainPartFile= fileHandler.compress(saveFile,passwd,compressmethod_key,beans,subsize,unit);
                                        }
                                    }
                                    if(!mainPartFile.mainFile.equals(saveFile_g)&&saveFile_g.exists()){
                                        Utils.del(saveFile_g.getAbsolutePath());
                                        mainPartFile.mainFile.renameTo(saveFile_g);
                                        mainPartFile.mainFile=saveFile_g;
                                        fileHandler.batchRenamePartsByMainFile(mainPartFile);
                                    }
                                    return mainPartFile;
                                }

                                @Override
                                protected void onPostExecute( FileHandler.MainPartFile  mainPartFile) {
                                    //todo  生成的saveFile应该在界面上 暂时
                                    String tip=getActivity().getResources().getString(R.string.compresscompletetip,
                                    taskName,mainPartFile.mainFile.getName());
                                    Toast.makeText(getActivity(),tip,Toast.LENGTH_SHORT).show();
                                    if(compressedFileBean.getParentPath().equals(findPathPathOnAtionbarLayout().getText())){
                                        refresh();
                                    }
                                    CompressFileFragment compressFileFragment=
                                            (CompressFileFragment) ((GetFragment)getActivity()).get(Utils.COMPRESSFRAG_TAB_INDEX);
                                    if(mainPartFile.mainFile.equals(compressFileFragment.getRootFile())){
                                        compressFileFragment.refresh();
                                    }
                                    enablefooterBtnes();
                                }

                                @Override
                                protected boolean onCancelled(FileHandler.MainPartFile mainPartFile) {
                                    String mainFilePath=mainPartFile.mainFile.getAbsolutePath();
                                    boolean deledMainFile=Utils.del(mainFilePath);
                                    boolean deledpart=false;
                                    for(String part:mainPartFile.partFiles){
                                        deledpart= Utils.del(part);
                                        deledMainFile=deledMainFile&&deledpart;
                                        if(!deledMainFile){
                                            break;
                                        }
                                    }
                                    if(deledMainFile){
                                        Intent i=new Intent(Utils.NOTIFYFILESYSTEMCHANGEINCURRENTDIR_ACTION);
                                        i.putExtra("currentPath",mainPartFile.mainFile.getParent());
                                        getActivity().sendBroadcast(i);
                                    }
                                    enablefooterBtnes();
                                    return deledMainFile;
                                }
                            };
                            String tip=getActivity().getResources().getString(R.string.starttasktip,
                                    taskName);
                            Toast.makeText(getActivity(),tip,Toast.LENGTH_SHORT).show();
                            task.execute(MyApplication.getMyApplication(),taskName);
                        }
                    };

                    if(saveFile_g.exists()){
                        GenerateDialog.BtnBean btnBean1=new GenerateDialog.BtnBean();
                        btnBean1.setBtnText(getActivity().getText(R.string.verify_title).toString());
                        btnBean1.setListener(verifyOkListener);
                        GenerateDialog.BtnBean btnBean2=new GenerateDialog.BtnBean();
                        btnBean2.setBtnText(getActivity().getText(R.string.verify_modify).toString());
                        btnBean2.setListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent i=new Intent(getActivity(),OperationCompressActivity .class);
                                //todo  bean信息要传过去
                                i.putExtra("bean",compressedFileBean);
                                i.putParcelableArrayListExtra("beans",
                                        (ArrayList<? extends android.os.Parcelable>) beans);
                                i.putExtra("handler",fileHandlerClsName);
                                i.putExtra("passwd",passwd);
                                i.putExtra("compressmethod_key",compressmethod_key);

                                i.putExtra("subsize",subsize);
                                i.putExtra("unit",unit);
                                i.putExtra("saveName",saveName);
                                i.putExtra("nameOfFormat",nameOfFormat);
                                startActivityForResult(i, SysFileFragment.REQUESTCODE);
                            }
                        });
                        GenerateDialog.BtnBean btnBean3=new GenerateDialog.BtnBean();
                        btnBean3.setBtnText(getActivity().getText(R.string.verify_cancle).toString());
                        btnBean3.setListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                enablefooterBtnes();
                                //Toast.makeText(getActivity(),"取消任务:"+taskName,Toast.LENGTH_SHORT).show();
                            }
                        });
                        GenerateDialog.BtnBean btnBean[]=new GenerateDialog.BtnBean[]{
                                btnBean1,
                                btnBean2,
                                btnBean3
                        };
                        StringBuilder sb1=new StringBuilder(saveName);
                        sb1.append(".").append(nameOfFormat);
                        String tip=getActivity().getResources().getString(R.string.overrides_asktip,sb1.toString());
                        GenerateDialog.createVerifyDialog(getActivity(),tip,btnBean).show();
                    }else{
                        verifyOkListener.onClick(null);
                    }
                }else if(footer3.getTag(tag).equals(extract1)){
                    navigateToCompressFrgAble=true;
                    if(activity instanceof GetFragment){
                        GetFragment getCorrespondFragment= (GetFragment) activity;
                        CompressFileFragment fragment= (CompressFileFragment) getCorrespondFragment.
                                get(Utils.COMPRESSFRAG_TAB_INDEX);
                        fragment.extractBeans(currentDirStr,new CompressFileFragment.Callback() {
                            @Override
                            public void callback(boolean isSuccess,String saveDirName) {
                                if(isSuccess){
                                    Toast.makeText(getActivity(),"提取成功,生成目录:"+saveDirName,
                                            Toast.LENGTH_SHORT).show();
                                    if(currentDirStr.equals(findPathPathOnAtionbarLayout().getText())){
                                        refresh();
                                    }
                                }else{
                                    Toast.makeText(getActivity(),"提取失败",Toast.LENGTH_SHORT).show();
                                }
                                enablefooterBtnes();
                            }
                        });
                    }
                }
                enableMlistViewCheckbox(true);
                cancelAllMlistViewCheckbox();
                mListView.setLongClickable(true);
                if(footer2.getVisibility()==View.VISIBLE){
                    footer2.setVisibility(View.GONE);
                }
                if(footer3.getVisibility()==View.VISIBLE){
                    footer3.setVisibility(View.GONE);
                }
                break;
            case R.id.footer2_1:
                HeaderViewListAdapter hAdapter= (HeaderViewListAdapter) mListView.getAdapter();
                FileInfoAdapter fileInfoAdapter= (FileInfoAdapter) hAdapter.getWrappedAdapter();
                Map<Integer,FileInfoAdapter.CheckBoxBoolean> selectCheckboxes
                        =fileInfoAdapter.getSelectedCheckboxes();
                Set<Integer> selectpositions =selectCheckboxes.keySet();
                ArrayList<FileInfoBean> beans1=new ArrayList<FileInfoBean>();
                for(int i:selectpositions){
                    FileInfoBean bean= fileInfoAdapter.getItem(i);
                    beans1.add(bean);
                }

                Intent i=new Intent(getActivity(),OperationCompressActivity .class);
                //todo  bean信息要传过去
                i.putParcelableArrayListExtra("beans",beans1);
                startActivityForResult(i, SysFileFragment.REQUESTCODE);
                break;
            case R.id.footer2_2:
                v.setEnabled(false);
                HeaderViewListAdapter headerViewListAdapter=
                        (HeaderViewListAdapter) mListView.getAdapter();
                final FileInfoAdapter fileInfoAdapter1=
                        (FileInfoAdapter) headerViewListAdapter.getWrappedAdapter();
                Map<Integer,FileInfoAdapter.CheckBoxBoolean> selectedCheckboxes=
                        fileInfoAdapter1.getSelectedCheckboxes();
                final List<Integer> selectedPositions= new ArrayList<Integer>(selectedCheckboxes.keySet());
                final StringBuilder stringBuilder=new StringBuilder("删除:");
                if(selectedPositions.size()>0){
                    FileInfoBean bean= fileInfoAdapter1.getItem(selectedPositions.get(0));
                    stringBuilder.append(bean.getFileName()).
                            append(getActivity().getResources().getString(R.string.omit));
                }
                View.OnClickListener yesListener=new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showCoverProgress(true,"删除中...");
                        AsyncTask<Object,Object,Boolean> asyncTask=new AsyncTask<Object, Object, Boolean>() {
                            @Override
                            protected Boolean doInBackground(Object... params) {
                                boolean bv=true;
                                for (int i : selectedPositions) {
                                    FileInfoBean bean = fileInfoAdapter1.getItem(i);
                                    StringBuilder sb=new StringBuilder(bean.getParentPath()).
                                            append(File.separator).append(bean.getFileName());
                                    String fileName=Utils.normalizePath(sb.toString());
                                    if(!bean.isDir()){
                                        fileName=Utils.dropTailStr(fileName,File.separator);
                                    }
                                    boolean result = Utils.del(fileName);
                                    if (!result) {
                                        bv=result;
                                        break;
                                    }
                                }
                                return bv;
                            }
                            @Override
                            protected void onPostExecute(Boolean aBoolean) {
                                showCoverProgress(false,null);
                                if(aBoolean){
                                    Toast.makeText(getActivity(),
                                            getActivity().getString(R.string.success_del),
                                            Toast.LENGTH_SHORT).show();
                                }else{
                                    Toast.makeText(getActivity(),
                                            getActivity().getString(R.string.fail_del),
                                            Toast.LENGTH_SHORT).show();
                                }
                                refresh();
                                if(footer2.getVisibility()==View.VISIBLE){
                                    footer2.setVisibility(View.GONE);
                                }
                                footer2_2.setEnabled(true);
                            }
                        };
                        Toast.makeText(getActivity(),stringBuilder.toString(),Toast.LENGTH_SHORT).show();
                        asyncTask.execute();
                    }
                };
                AlertDialog alertDialog= GenerateDialog.createVerifyDialog(getActivity(),
                        getActivity().getString(R.string.confiremdel),yesListener, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                footer2_2.setEnabled(true);
                            }
                        });
                alertDialog.show();
                break;
        }
    }

    private void executeExtract(
                                 final File currentDir,
                                 final String saveName,
                                 final List<FileInfoBean> datas,
                                 final StringBuilder taskNameSb){
        final StringBuilder taskNameSb1=new StringBuilder(taskNameSb);
        MyAsyncTask task= new MyAsyncTask<String, Object, File>() {
            private String msg="";
            @Override
            protected File doInBackground(String... params) {
                String saveName1=saveName;
                if(params!=null&&params.length>0){
                    saveName1=params[0]==null?saveName:params[0];
                }
                File targetDir=new File(currentDir,saveName1);
                for(FileInfoBean bean:datas){
                    if(isCancelled()){
                        return targetDir;
                    }
                    try{
                        bean.getCompressFileHandler().extractAll(targetDir,bean);
                    }catch (MyException e){
                        if(e.getCode()==MyException.FAIL_EXTRACT_BYPASSWDERROR){
                            msg="解压出错密码错误!";
                            return null;
                        }
                    }
                }
//                File f= fileHandler.extract(new File(currentDir,saveName1),datas);
                return targetDir;
            }
            @Override
            protected void onPostExecute(File f) {
                if(f==null){
                    Toast.makeText(getActivity(),
                            taskNameSb1.append(msg).toString(),
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(getActivity(),
                        taskNameSb1.append("完成,当前目录下生成目录:").
                                append(f.getName()).toString(),
                        Toast.LENGTH_SHORT).show();
                refresh();
                enablefooterBtnes();
            }

            @Override
            protected boolean onCancelled(final File file) {
                 boolean b= Utils.del(file.getAbsolutePath());
                if(b){
                    Intent i=new Intent(Utils.NOTIFYFILESYSTEMCHANGEINCURRENTDIR_ACTION);
                    i.putExtra("currentPath",file.getParent());
                    getActivity().sendBroadcast(i);
                }
                enablefooterBtnes();
                return b;
            }
        };
        Object[] params=new String[]{saveName};
        Toast.makeText(getActivity(),
                taskNameSb.append(" 启动,提交到任务列表").toString(),Toast.LENGTH_SHORT).show();
        task.execute((MyApplication) getActivity().getApplication(),
                taskNameSb.append(" 启动,提交到任务列表").toString(),params);
    }

    private void inputPasswdToFileInfobean(final ArrayList<FileInfoBean> beans,
                                              final File currentDir,
                                              final String saveName,
                                              final String preMsg){
        //todo  以后...
        showCoverProgress(true,"检验是否加密");
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                File path=new File(currentDir,saveName);
                if(path.exists()){
                    Utils.del(path.getAbsolutePath());
                }

                isEncriedBeans=new ArrayList<FileInfoBean>();
                isNotEncriedBeans=new ArrayList<FileInfoBean>();
                for(FileInfoBean bean:beans){
                    StringBuilder sb=new StringBuilder(bean.getParentPath());
                    sb.append(File.separator).append(bean.getFileName());
                    File file=new File(Utils.normalizePath(sb.toString()));
                    if(ExecuteFileHandler.getInstance().isEncried(file)){
                        isEncriedBeans.add(bean);
                    }else{
                        isNotEncriedBeans.add(bean);
                    }
                }

                getActivity().runOnUiThread(new Thread(new Runnable() {
                    @Override
                    public void run() {
                        showCoverProgress(false,null);
                    }
                }));

                if(isEncriedBeans!=null&&!isEncriedBeans.isEmpty()){
                    Intent i=new Intent(getActivity(),InputPasswdActivity.class);
                    i.setAction(INPUTPASSWD_ACTION);
                    i.putParcelableArrayListExtra("beans",isEncriedBeans);
                    i.putExtra("currentDir",currentDir.getAbsolutePath());
                    i.putExtra("saveName",saveName);
                    i.putExtra("preMsg",preMsg);
                    i.putExtra("requestcode",REQUESTCODE_PASSWD);
                    startActivityForResult(i, REQUESTCODE_PASSWD);
                }else{
                    getActivity().runOnUiThread(new Thread(new Runnable() {
                        @Override
                        public void run() {
                            executeExtract(currentDir,saveName,beans,new StringBuilder(preMsg));
                        }
                    }));
                }
            }
        });
        thread.start();
    }

    @Override
    protected void onSubLongItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    protected LinearLayout findPathlayoutOnAtionbarLayout() {
        LinearLayout pathlayout1= (LinearLayout) actionbarLayout.findViewById(R.id.pathlayout1);
        return pathlayout1;
    }

    @Override
    protected TextView findPathPathOnAtionbarLayout() {
        TextView textView= (TextView) actionbarLayout.findViewById(R.id.path1);
        return textView;
    }

    @Override
    public void disableExtractBtn(Map<Integer, FileInfoAdapter.CheckBoxBoolean> selected) {
        HeaderViewListAdapter headerViewListAdapter= (HeaderViewListAdapter) mListView.getAdapter();
        FileInfoAdapter adapter= (FileInfoAdapter) headerViewListAdapter.getWrappedAdapter();
        Map<Integer,FileInfoAdapter.CheckBoxBoolean> map= selected;
        Set<Integer> set= map.keySet();
        boolean result=true;
        for (int i:set){
            FileInfoBean bean= adapter.getItem(i);
            if(!bean.isCompressed()){
                result=false;
                break;
            }
        }
        footer2_4.setEnabled(result);
        /*if(extractTv.isEnabled()){

        }*/
    }

    public void selectDir(){
        enableMlistViewCheckbox(false);
        mListView.setLongClickable(false);
        Toast.makeText(getActivity(),
                getActivity().getResources().getString(R.string.selectdir),Toast.LENGTH_SHORT).show();
        footer3.setVisibility(View.VISIBLE);
        footer3.setTag(tag,extract1);
        navigateToCompressFrgAble=false;
    }


}
